package com.entor.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Map;

import java.net.URLEncoder;

import com.alibaba.fastjson.JSON;

/**
 * 发送HTTP的请求，访问controller，并获取返回值json对象
 * @author Administrator
 *
 */
public class HttpPostUtil {
	
	public static String doPostRequest(String path,Object obj) {
		
		StringBuilder result = new StringBuilder();
		PrintWriter out = null;
		BufferedReader in = null;
		try {
			
			String json = JSON.toJSONString(obj);
			Map<String, Object> map = JSON.parseObject(json);
			String param = "";
			boolean b = false;
			for(String key:map.keySet()) {
				if(b) {
					param += "&";
				}
				param += key+"="+map.get(key);
				b = true;
			}
			
			String address = "http://127.0.0.1:8088/urcs/"+path+"?"+param;
			//远程路径访问连接
			URL url = new URL(address);
			//打开连接
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			//设置必须的参数
			connection.setDoInput(true);
			connection.setDoOutput(true);
			
			//设置连接超时时间
			connection.setReadTimeout(10*1000);
			connection.setConnectTimeout(10*1000);
			
			//设置提交方式
			connection.setRequestMethod("POST");
			
			//防止出现EOFException错误
			connection.setRequestProperty("Content-type", "application/x-java-serialized-object");
			//设置传递参数使用json
			//connection.setRequestProperty("Content-type", "application/json");
			
			//执行链接
			connection.connect();
			//把参数写入输出流
			//out = new PrintWriter(connection.getOutputStream());
			OutputStream os = connection.getOutputStream();
			//os.write(json.getBytes());
			os.flush();
			//判断链接的状态码
			if(connection.getResponseCode()==200) {//说明链接成功
				in = new BufferedReader(
						new InputStreamReader(connection.getInputStream())
						);
				//循环读取流对象的内容
				String line = "";
				while((line=in.readLine())!=null) {
					result.append(line);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
		return result.toString();
		
	}

}
